package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 查询单个分类下文章

// 查询分类是否存在
func CheckCate(c *gin.Context) {
	name := c.Query("name") // query数据
	code := model.CheckCate(name)
	Response(c, code, "")
}

// 添加分类
func AddCate(c *gin.Context) {
	data := &model.Category{}
	c.ShouldBindJSON(data)
	code = model.CheckCate(data.Name)
	if code == errmsg.SUCESS {
		code = model.CreateCate(data)
	}

	Response(c, code, data)
}

// 查询分类列表
func GetCate(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	if pageNum == 0 {
		pageNum = -1
	}
	cate, code := model.GetCate(pageSize, pageNum)
	Response(c, code, cate)
}

// 编辑分类
func EditCate(c *gin.Context) {
	var data model.Category
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)

	// 下面这句话可以放到钩子函数中，但是放在这里代码可读性更高
	code = model.CheckCate(data.Name)
	if code == errmsg.SUCESS {
		code = model.EditCate(id, &data)
	}
	Response(c, code, "")
}

// 删除分类
func DeleteCate(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteCate(id)
	Response(c, code, "")
}
